//
//  MBPraiseEmitterBtn.swift
//  Merchants
//
//  Created by kingly on 2020/7/27.
//  Copyright © 2020 VALUABLE JADE(SHENZHEN) JEWELRY JADE Co.,Ltd. All rights reserved.
//

import UIKit

class MBPraiseEmitterBtn : UIButton {
    
    var explosionLayer: CAEmitterLayer
    
    override var isSelected: Bool{
        didSet{
            //            执行动画
            explosionAni()
        }
    }
    
    override init(frame: CGRect) {
        explosionLayer = CAEmitterLayer.init()
        super.init(frame: frame)
        setupExplosion()
    }
    
    required init?(coder: NSCoder) {
        explosionLayer = CAEmitterLayer.init()
        super.init(coder: coder)
        setupExplosion()
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //    MARK: - 创建发射层
    func setupExplosion(){
        
        explosionLayer.name = "explosionLayer"
        
        //        发射源的形状
        explosionLayer.emitterShape = CAEmitterLayerEmitterShape.circle
        //        发射模式
        explosionLayer.emitterMode = CAEmitterLayerEmitterMode.outline
        //        发射源大小
        explosionLayer.emitterSize = CGSize.init(width: 10, height: 0)
        
        //        渲染模式
        explosionLayer.renderMode = CAEmitterLayerRenderMode.oldestFirst
        explosionLayer.masksToBounds = false
        explosionLayer.birthRate = 0
        //        发射位置
        explosionLayer.position = CGPoint.init(x: frame.size.width/2, y: frame.size.height/2)
        explosionLayer.zPosition = -1
        layer.addSublayer(explosionLayer)
        
    }
    
    //发射的动画
    func explosionAni(){
        let animation = CAKeyframeAnimation(keyPath: "transform.scale")
        if isSelected {
            animation.values = [1.5,0.8,1.0,1.2,1.0]
            animation.duration = 0.5
            
            startAnimation()
        } else {
            animation.values = [0.8,1.0]
            animation.duration = 0.4
        }
        
        animation.calculationMode = CAAnimationCalculationMode.cubic
        layer.add(animation, forKey: "transform.scale")
    }
    
    func startAnimation(){
        explosionLayer.beginTime = CACurrentMediaTime()
        explosionLayer.birthRate = 1
        perform(#selector(MBPraiseEmitterBtn.stopAnimation), with: nil, afterDelay: 0.15)
    }
    
    @objc func stopAnimation(){
        explosionLayer.birthRate = 0
    }
}
